const Service = require('egg').Service;
const { error, success } = require('../utils/response.js')
const moment = require('moment')

class InvatationService extends Service {
    // 获取帖子 分页加筛选
    async getPage(info, ctx) {
        const limit = info.limit || 10;
        const page = info.page || 1;
        let { title } = info;
        if (title === '') title = null;
        // 获取分页数据
        const res = await this.app.mysql.query(`select * from user u,invitation i where (u.id=i.userId) and (title like concat('%',?,'%') or ? is null) order by updateTime desc limit ? offset ?`, [title, title, Number(limit), (page - 1) * limit]);
        // 获取总页数
        const resTotal = await this.app.mysql.query(`select count(id) from invitation`);
        const totalPage = Math.ceil(resTotal[0]['count(id)'] / limit);
        res.forEach(element => {
            delete element.password
            element.updateTime = moment(Number(element.updateTime)).format('YYYY-MM-DD HH:mm:ss');
            element.createTime = moment(Number(element.createTime)).format('YYYY-MM-DD HH:mm:ss');
        });
        success(ctx, '获取成功', { totalPage, currentPage: Number(page), total: resTotal[0]['count(id)'], data: res })
    }

    // 添加帖子功能  需要登录权限
    async add(info, ctx) {
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        const now = moment().valueOf();
        const res = await this.app.mysql.insert('invitation', { ...info, userid: userInfo.id, createTime: now, updateTime: now })
        if (res.affectedRows !== 1) error(ctx, '添加评论失败！请检查后台服务')
        success(ctx, '添加成功！')
    }
    // 删除帖子功能  需要管理员权限
    async delete(info, ctx) {
        // 只有status为超管(3)的才能获取这个接口
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        if (userInfo.status !== 2) return error(ctx, '没有该接口的权限')
        const {id} = info
        const res = await this.app.mysql.delete('invitation',{id});
        if(res.affectedRows !== 1) error(ctx, '删除帖子！请检查后台服务')
        success(ctx, '删除成功')
    }
}
module.exports = InvatationService;